
var url = "http://dbadmin.haiziwang.com/sqlquery"
var pageContext = {
  "instance_name_html": "",
  "cookies": "",
  "getCookie": function (name) {
    var cookieValue = null;
    var cookies = this.cookies.split(';');
    for (var i = 0; i < cookies.length; i++) {
      var cookie = jQuery.trim(cookies[i]);
      // Does this cookie string begin with the name we want?
      if (cookie.substring(0, name.length + 1) === (name + '=')) {
        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
        break;
      }
    }
    return cookieValue;
  }
}

function getCookie(name) {
  var cookieValue = null;
  if (document.cookie && document.cookie !== '') {
    var cookies = document.cookie.split(';');
    for (var i = 0; i < cookies.length; i++) {
      var cookie = jQuery.trim(cookies[i]);
      // Does this cookie string begin with the name we want?
      if (cookie.substring(0, name.length + 1) === (name + '=')) {
        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
        break;
      }
    }
  }
  return cookieValue;
}



chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  if (request.action == 'init_instance_name') {
    pageContext.instance_name_html = request.data;
    sendResponse({ farewell: 'ok' + '444' });
  } else if (request.action == 'init_page_cookie') {
    chrome.cookies.getAll({
      url: request.data
    }, (cks) => {
      let cookie = cks.map((item) => {
        return item.name + "=" + item.value
      }).join(";") + ";";
      console.log(cookie)
      pageContext.cookieStore = cookie;
      sendResponse({ farewell: 'ok' + '444' + cookie });
    });
    sendResponse({ farewell: 'ok' + '444' });
  } else if (request.action == 'init') {

    var data = request.data;
    chrome.cookies.getAll({
      url: data.url
    }, (cks) => {
      let cookie = cks.map((item) => {
        return item.name + "=" + item.value
      }).join(";") + ";";
      console.log(cookie)
      pageContext.cookies = cookie
      $.ajaxSetup({
        headers: { "X-CSRFToken": pageContext.getCookie("csrftoken") }
      });

      sendResponse({ farewell: 'ok' + '444' + cookie });
    });
    sendResponse({ farewell: 'ok' + '444' });
  }


  {
    sendResponse({ farewell: 'goodbye' });
  }
});


function ajax(config) {
  $.ajax({
    url: config.url,
    cache: false,
    type: config.type,
    data: config.data,
    dataType: config.dataType,
    success: config.success,
    complete: config.complete,
    error: config.error
  });
}




